package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.Dto.MriqcConfigDto;
import com.ruoyi.system.Dto.TasKConfigDto;
import com.ruoyi.system.Dto.TaskSubAllDto;
import com.ruoyi.system.Dto.TaskSubDto;
import com.ruoyi.system.annotation.FileParam;
import com.ruoyi.system.annotation.FileValid;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAllTaskService;
import com.ruoyi.system.service.IMriqcConfigService;
import com.ruoyi.system.service.ITaskSubAllService;
import com.ruoyi.system.utils.Util;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.system.controller.iBrainController.deleteFile;
import static com.ruoyi.system.utils.DirectoryUtil.deleteDirectory;
import static com.ruoyi.system.utils.DirectoryUtil.traverseDirectories;
import static com.ruoyi.system.utils.Util.*;


@RequestMapping("/mriqc")
@RestController
public class mriqcController extends BaseController{

    @Autowired
    private IAllTaskService iAllTaskService;
    @Autowired
    private ITaskSubAllService iTaskSubAllService;
    @Autowired
    private IMriqcConfigService mriqcConfigService;




    @PostMapping("/upload")
    @FileValid
    public Map<String,String> handleFileUpload(@FileParam MultipartFile file, @Param("taskId") Long taskId) {
        Map<String,String> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("error","上传空文件，请检查");
            return result;
        }
        try {
            String fileName = file.getOriginalFilename();
            String filePath = Constants.mriqcpth+File.separator+fileName;
            File dest = new File(filePath);
            file.transferTo(dest); //保存文件到指定路径
            //result.put("success",filePath);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();
            String folder = Constants.mriqcpth+File.separator+userId+"_"+generateRandomString(10);
            // 使用Paths.get()方法创建Path对象
            Path newDirectoryPath = Paths.get(folder);
            // 创建文件夹
            try {
                Files.createDirectories(newDirectoryPath); // 使用createDirectories()创建多级目录
                unzip(filePath, folder);
                List<String> subjectlist = traverseDirectories(folder);
                if(subjectlist.size()==0){
                    deleteDirectory(newDirectoryPath);
                    Path delezip = Paths.get(filePath);
                    Files.delete(delezip);
                    result.put("error","文件夹内部格式错误或者上传空文件，请检查");
                    return result;
                }

                if(iAllTaskService.addtasksub(taskId,subjectlist,folder,Constants.mriqcpth)){
                    Path delezip = Paths.get(filePath);
                    Files.delete(delezip);
                    result.put("success","上传成功");
                    return result;
                }

                deleteDirectory(newDirectoryPath);
                Path delezip = Paths.get(filePath);
                Files.delete(delezip);
                result.put("error","上传同名被试，请检查");
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            }

            return result;
        } catch (IOException e) {
            result.put("error","500错误");
            return result;
        }
    }


    @GetMapping("/getaskid")
    public Map<String,Object> getaskid(){
        Map<String, Object> result = new HashMap<>();
        AllTask allTask = iAllTaskService.gettaskid(1l);  //1L mriqc任务
        Long queue = allTask.getQueue();
        Long status = allTask.getStatus();
        result = Util.returnmap(status,queue);
        result.put("taskId",allTask.getId());
        return result;
    }

    @GetMapping("/queueloader")
    public Map<String,Object> queueloader(@RequestParam Integer allTaskId){
        Map<String, Object> result = new HashMap<>();
        AllTask allTask = iAllTaskService.selectAllTaskById(Long.valueOf(allTaskId));  //获取任务
        Long queue = allTask.getQueue();
        Long status = allTask.getStatus();
        result = Util.returnmap(status,queue);
        return result;
    }

    @GetMapping("/progressloader")
    public Map<String, Object> progressloader(@RequestParam Integer allTaskId) {
        Map<String, Object> result = new HashMap<>();
        AllTask allTask = iAllTaskService.selectAllTaskById(Long.valueOf(allTaskId));
        Long queue = allTask.getQueue();
        Long status = allTask.getStatus();
        result = Util.returnmap(status,queue);
        if(allTask.getStatus()==4){
            String time = allTask.getOverTime();
            long countdown = remaintime(time);
            if(countdown<=0)
                countdown=0;
            result.put("countdown",countdown);
        }
        TaskSubAll taskSubAll = new TaskSubAll();
        taskSubAll.setTaskId(Long.valueOf(allTaskId));
        List<TaskSubAllDto> taskSubAllDtos = new ArrayList<>();
        List<TaskSubAll> taskSubAlls = iTaskSubAllService.selectTaskSubAllList(taskSubAll);
        for(TaskSubAll t:taskSubAlls){
            TaskSubAllDto taskSubAllDto = new TaskSubAllDto();
            if(t.getIsover()==null)
                taskSubAllDto.setIsover(false);
            if(t.getIsover()!=null){
                if(t.getIsover()==1l){
                    taskSubAllDto.setIsover(true);
                }
            }
            taskSubAllDto.setStatus(t.getStatus());
            taskSubAllDto.setId(t.getId());
            taskSubAllDto.setTaskId(t.getTaskId());
            taskSubAllDto.setSubname(t.getSubname());
            taskSubAllDto.setStartTime(t.getStartTime());
            taskSubAllDto.setEndTime(t.getEndTime());
            taskSubAllDtos.add(taskSubAllDto);
        }
        result.put("userList",taskSubAllDtos);
        return result;
    }


    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody TaskSubAll taskSubAll) {
        AllTask allTask = iAllTaskService.selectAllTaskById(taskSubAll.getTaskId());
        String task = allTask.getId().toString();
        String name = iTaskSubAllService.selectTaskSubAllById(taskSubAll.getId()).getSubname();
        File file = new File(Constants.mriqcpth+File.separator+task+File.separator+name);//输入要删除文件目录的绝对路径
        if (!deleteFile(file)) {
            return AjaxResult.error("删除失败");
        }
        iTaskSubAllService.deleteTaskSubAllById(taskSubAll.getId());
        return AjaxResult.success();
    }

    @PostMapping("/batchDelete")
    public AjaxResult batchDelete(@RequestBody TaskSubAllDto taskSubAllDto) {
        AllTask allTask = iAllTaskService.selectAllTaskById(taskSubAllDto.getTaskId());
        String task = allTask.getId().toString();
        int size = taskSubAllDto.getIds().size();
        Integer[] i = new Integer[size];
        for(int a=0;a<size;a++){
            i[a] = taskSubAllDto.getIds().get(a);
        }
        for(int l=0;l<i.length;l++){
            String name = iTaskSubAllService.selectTaskSubAllById(i[l].longValue()).getSubname();
            File file = new File(Constants.mriqcpth+File.separator+task+File.separator+name);//输入要删除文件目录的绝对路径
            if (!deleteFile(file)) {
                return AjaxResult.error("删除失败");
            }
        }
        iTaskSubAllService.deleteTaskSubAllByIds(i);
        return AjaxResult.success();
    }


    @GetMapping("/getuserlist")
    public Map<String,Object> getuserlist(@RequestParam Integer AllTaskId){
        Map<String, Object> result = new HashMap<>();
        TaskSubAll taskSubAll = new TaskSubAll();
        taskSubAll.setTaskId(Long.valueOf(AllTaskId));
        List<TaskSubAll> taskSubAlls = iTaskSubAllService.selectTaskSubAllList(taskSubAll);
        List<TaskSubAllDto> taskSubAllDtos = new ArrayList<>();
        MriqcConfig mriqcConfigtemp = new MriqcConfig();
        mriqcConfigtemp.setAllTaskId(Long.valueOf(AllTaskId));
        MriqcConfig mriqcConfig = mriqcConfigService.selectNew(mriqcConfigtemp);
        AllTask allTask = iAllTaskService.selectAllTaskById(Long.valueOf(AllTaskId));
        if(mriqcConfig!=null&&(allTask.getStatus()==4||allTask.getStatus()==5)){
            if(allTask.getStatus()==4){
                String time = allTask.getOverTime();
                long countdown = remaintime(time);
                if(countdown<=0)
                    countdown=0;
                result.put("countdown",countdown);
            }
            for(TaskSubAll t:taskSubAlls){
                TaskSubAllDto taskSubAllDto = new TaskSubAllDto();
                if(t.getIsover()==null)
                    taskSubAllDto.setIsover(false);
                if(t.getIsover()!=null){
                    if(t.getIsover()==1l){
                        taskSubAllDto.setIsover(true);
                    }
                }
                taskSubAllDto.setStatus(t.getStatus());
                taskSubAllDto.setId(t.getId());
                taskSubAllDto.setTaskId(t.getTaskId());
                taskSubAllDto.setSubname(t.getSubname());
                taskSubAllDto.setStartTime(t.getStartTime());
                taskSubAllDto.setEndTime(t.getEndTime());
                taskSubAllDtos.add(taskSubAllDto);
            }
            result.put("userList",taskSubAllDtos);
            return result;
        }
        result.put("userList",taskSubAlls);
        return result;
    }


    @PostMapping ("/run")
    public Map<String, Object> run(@RequestBody MriqcConfigDto mriqcConfigDto){
        Map<String, Object> result = new HashMap<>();
        int size = mriqcConfigDto.getIds().size();
        if(size==0){
            result.put("error",1);
            return result;
        }
        Integer[] i = new Integer[size];
        String subjects="";
        for(int index=0;index<size;index++){
            i[index] = mriqcConfigDto.getIds().get(index);
            subjects=subjects+iTaskSubAllService.selectTaskSubAllById(i[index].longValue()).getSubname()+",";
        }
        subjects = subjects.substring(0,subjects.length()-1);
        MriqcConfig mriqcConfig = new MriqcConfig();
        mriqcConfig.setAllTaskId(mriqcConfigDto.getAllTaskId());
        mriqcConfig.setSubject(subjects);
        mriqcConfigService.insertMriqcConfig(mriqcConfig);
        iAllTaskService.updateAlltaskstatus(mriqcConfigDto.getAllTaskId());
        AllTask allTask = iAllTaskService.selectAllTaskById(mriqcConfigDto.getAllTaskId());
        Long queue = allTask.getQueue();
        Long status = allTask.getStatus();
        result = Util.returnmap(status,queue);
        return result;
    }


    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam Integer taskId, @RequestParam String subname) throws IOException {
        String dir="";
        AllTask allTask = iAllTaskService.selectAllTaskById(Long.valueOf(taskId));
        String filename = subname+"_result_report.pdf";
        dir = Constants.mriqcpth+File.separator+"result"+File.separator+taskId+"_"+subname;

        Path filePath = Paths.get(dir,filename);
        File file = filePath.toFile();
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }




}
